package com.qrxl.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qrxl.util.JGAssert;
import com.qrxl.user.entity.Role;
import com.qrxl.user.entity.RoleMenu;
import com.qrxl.user.mapper.RoleMenuMapper;
import com.qrxl.user.service.IRoleMenuService;
import com.qrxl.user.service.IRoleService;
import com.qrxl.user.vo.UserLoginInfo;
import com.qrxl.user.vo.req.RoleRelMenuReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单关联 服务实现类
 * </p>
 *
 * @author friday
 * @since 2020-12-05
 */
@Service
@Slf4j
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {
    @Autowired
    IRoleService roleService;

    @Override
    public void relMenus(RoleRelMenuReq req, UserLoginInfo userLoginInfo) {
        //只允许,角色创建人关联
        Role role = roleService.getById(req.getRoleId());
        JGAssert.isTrue(userLoginInfo.getLoginName().equals(role.getOperator()), "只允许,角色创建人关联");

        RoleMenu cond = new RoleMenu();
        cond.setRoleId(req.getRoleId());
        List<RoleMenu> dbList = baseMapper.selectList(Wrappers.query(cond));
        List<RoleMenu> insertList = req.getMenuIdList().stream()
                .filter(one -> !dbList.stream().anyMatch(two -> two.getRoleId().equals(one)))
                .map(one -> {
                    RoleMenu insert = new RoleMenu();
                    insert.setRoleId(req.getRoleId());
                    insert.setMenuId(one);
                    return insert;
                }).collect(Collectors.toList());

        List<String> deleteList = dbList.stream()
                .filter(one -> !req.getMenuIdList().stream().anyMatch(two -> two.equals(one.getMenuId())))
                .map(RoleMenu::getId).collect(Collectors.toList());

        deleteList.forEach(id -> {
            baseMapper.deleteById(id);
            log.info("角色关联菜单，删除：id=" + id);
        });
        insertList.forEach(one -> {
            baseMapper.insert(one);
            log.info("角色关联菜单，删除：obj=" + JSON.toJSONString(one));
        });
    }
}
